package com.doucat.support.component.fragment.base;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.core.widget.ContentLoadingProgressBar;
import androidx.fragment.app.Fragment;

import com.doucat.support.component.fragment.Refreshable;
import com.doucat.support.dialog.AskDialog;
import com.doucat.support.dialog.TipDialog;
import com.doucat.support.model.inter.InterfaceView;
import com.doucat.support.thread.WorkersThread;
import com.tonly.doucatlibrary.R;

import java.util.List;

/**
 * -----------------------------------------------------------------
 * Copyright (C) 2021-2031, by tonly, All rights reserved.
 * -----------------------------------------------------------------
 * File: SubFragment.java
 * Author: wangfy
 * Create: 2021/7/1 15:08
 */
public abstract class BaseFragment extends Fragment implements InterfaceView, Refreshable {
    protected String TAG=getClass().getSimpleName();
    protected String TAG_LIFE="fragment_life:"+getClass().getSimpleName()+"_";
    protected void print(String log){
        Log.d(TAG,log);
    }
    private Handler mainHandler;
    private WorkersThread threadPool;

    private TipDialog tipDialog;
    private AskDialog askDialog;
    private Toast toast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        print(TAG_LIFE+"onCreate");
        /**
         * loadThread延迟初始化
         * 消息会阻塞，发了不执行
         *
         * mainHandler不能保证调用的地方是UI线程，也就不能保证getMainLooper
         */
        threadPool=WorkersThread.getInstance();
        mainHandler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(isAdded()){
                    onGetMessage(msg);
                }
            }
        };
    }

    private View viewRoot;
    private FrameLayout fragmentContent;
    public ContentLoadingProgressBar progressLoading;
    private ViewGroup layoutEmpty;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        print(TAG_LIFE+"onCreateView");
        viewRoot = inflater.inflate(R.layout.fragment_base, container, false);
        fragmentContent = viewRoot.findViewById(R.id.fragmentContent);
        progressLoading = viewRoot.findViewById(R.id.progressLoading);
        layoutEmpty = viewRoot.findViewById(R.id.layoutEmpty);
        onRootViewCreate(inflater, fragmentContent,savedInstanceState);
        return viewRoot;
    }

    /**
     * 加载自定义布局
     * @param inflater
     * @param container
     * @param savedInstanceState
     */
    public abstract void onRootViewCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    /**
     * 从自定义布局中find，这样可以避免id的冲突，并更快的找到view
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T findViewById(int id){
        return fragmentContent.findViewById(id);
    }

    public void setBaseFragmentContentView(int layoutResID) {
        fragmentContent.removeAllViews();
        View.inflate(getContext(), layoutResID, fragmentContent);
    }
    @Override
    public void onResume() {
        super.onResume();
        print(TAG_LIFE+"onResume");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        print(TAG_LIFE+"onDestroy");
        mainHandler.removeCallbacksAndMessages(null);
        threadPool.shutdownNow();
        dismissAsk();
        dismissTip();
        dismissLoading();
    }

    @Override
    public void onDestroyView() {
        print(TAG_LIFE+"onDestroyView");
        super.onDestroyView();
    }
    @Override
    public void onAttach(Context context) {
        print(TAG_LIFE+"onAttach");
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
    /*****************************************多线程*******************************************/
    public void onGetMessage(Message message){

    }

    /**
     * @param runnable
     */
    public void runOnThread(Runnable runnable){
        threadPool.execute(runnable);
    }

    /**
     * @param runnable
     */
    public void runOnUiThread(Runnable runnable){
        if(isAdded()){
            mainHandler.post(runnable);
        }
    }

    /**
     * @param message
     */
    public void sendToMainThread(Message message){
        mainHandler.sendMessage(message);
    }

    /************************************************提示信息**********************************************/
    public void showAsk(String title, String leftString, View.OnClickListener leftClick, String rightString, View.OnClickListener rightClick){
        if(askDialog==null){
            askDialog=new AskDialog();
        }
        askDialog.setTitle(title)
                .setLeftButton(leftString,leftClick)
                .setRightButton(rightString,rightClick)
                .show(getActivity(),getChildFragmentManager());
    }
    public void dismissAsk() {
        if(askDialog!=null)askDialog.dismiss();
    }
    /**
     * 显示提示对话框
     */
    public void showTipDialog(String s) {
        if(tipDialog==null){
            tipDialog=new TipDialog();
        }
        tipDialog.setTitle(s)
                .show(getActivity(),getChildFragmentManager());
    }

    public void dismissTip(){
        if(tipDialog!=null)tipDialog.dismiss();
    }

    public void toast(String text){
        if(toast==null){
            //传入普通context，文字飘到别处，原因未知
            toast= Toast.makeText(getContext().getApplicationContext(),"",Toast.LENGTH_SHORT);
        }
        toast.setText(text);
        toast.show();
    }


    public void dismissLoading() {
        progressLoading.setVisibility(View.GONE);
    }
    public void showLoading() {
        progressLoading.setVisibility(View.VISIBLE);
    }

    /*************************************MVP*******************************************/
    @Override
    public void onStartRequest() {
        progressLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void onResponse() {
        progressLoading.setVisibility(View.GONE);
    }

    @Override
    public void onFailure(String str) {
        progressLoading.setVisibility(View.GONE);
        toast(str);
    }

    @Override
    public void onData(List data) {
        if(data==null||data.isEmpty()){
            layoutEmpty.setVisibility(View.VISIBLE);
        }else {
            layoutEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 完成请求，message code success 取消加载动画
     */
    @Override
    public void onSuccess(String str) {
        //根据业务逻辑对view进行操作，默认不做处理
    }

    /**
     * 完成请求，message code error 提示信息
     */
    @Override
    public void onFail(String str) {
        toast(str);
    }


    /**************************数据刷新**************************************/

    /**
     * 通知刷新数据
     */
    public void requestRefresh(){
        if(isAdded()){
            onRefresh();
        }
    }

    @Override
    public void onRefresh() {

    }

    public void replaceFragmentToContent(Fragment fragment){
        getChildFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentContent,fragment)
                .addToBackStack("")
                .commitAllowingStateLoss();
    }

    public void replaceFragment(int layout, Fragment fragment) {
        getChildFragmentManager()
                .beginTransaction()
                .replace(layout, fragment)
                .commitAllowingStateLoss();
    }

    public void removeFragment(Fragment fragment) {
        getChildFragmentManager()
                .beginTransaction()
                .remove(fragment)
                .commitAllowingStateLoss();
    }

    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
    }
}
